package com.cloud.shopping.tool;

import com.alibaba.fastjson.JSON;
import com.cloud.shopping.tool.encry.Aes;
import com.cloud.shopping.tool.encry.Base64;
import com.cloud.shopping.tool.encry.Md5;

import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author John.zhang
 * @version Id: Signature, v 1.0 2021/1/5 17:05 ZhiYong Exp $
 */
public class Signature {

    /**
     * 秘钥
     */
    private String secret;

    /**
     * 盐值
     */
    private String salt;


    public Signature(String secret, String salt) {
        this.secret = secret;
        this.salt = salt;
    }

    /***
     * 密文解密，并转成Map,并对Map数据进行验签
     * @param content content
     * @return Map
     */
    public Map<String,String> security(String content) throws Exception {
        //1.解密
        String decrypt =new String( Aes.encryptAndDecrypt(Base64.decodeURL(content), secret,2) , "UTF-8");
        //2.明文转Map并根据Key降序
        Map<String,String> decryptTreeMap = JSON.parseObject(decrypt, TreeMap.class);
        //3.验签
        String signature = decryptTreeMap.remove("signature");
        String localSignature = Md5.md5(JSON.toJSONString(decryptTreeMap),salt);
        //true 验签成功，false  验签失败
        return signature.equals(localSignature)? decryptTreeMap : null;
    }


    /**
     * Map加密，携带验签
     * @param dataMap dataMap
     * @return String
     * @throws Exception
     */
    public String security(Map<String,String> dataMap) throws Exception {
        //1.将dataMap转成TreeMap
        dataMap = JSON.parseObject(JSON.toJSONString(dataMap),TreeMap.class);
        //2.将TreeMap转成JSON
        String treeJson = JSON.toJSONString(dataMap);
        //3.执行MD5摘要加密
        String signature = Md5.md5(treeJson,salt);
        //4.摘要加密内容添加到dataMap中
        dataMap.put("signature",signature);
        //5.AES加密dataMap
        return Base64.encodeURL(Aes.encryptAndDecrypt(JSON.toJSONString(dataMap).getBytes(StandardCharsets.UTF_8),secret,1));
    }

}
